package com.enzo.pcms.login.dao.impl;

import com.enzo.pcms.base.dao.BaseDao;
import com.enzo.pcms.common.exception.DaoException;
import com.enzo.pcms.common.exception.DuplicateRecordException;
import com.enzo.pcms.common.util.ConsUtil;
import com.enzo.pcms.login.dao.UserDao;
import com.enzo.pcms.login.model.User;
import com.itool.util.StringUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("userDao")
public class UserDaoImpl extends BaseDao implements UserDao {
	public UserDaoImpl() {
		super();
	}

	public Integer insert(User user)throws DaoException {
		if(user!=null&&StringUtil.isNotEmpty(user.getEmail())){
			checkUserByNameOrEmail(user.getUsername(), user.getEmail());
			return (Integer)getSqlMapClientTemplate().insert("insert",user); 
		}else{
			throw new DaoException("DaoException:The email is empty.");
		}
	}
	
	@Override
	public void update(User user) throws DaoException {
	}

	@Override
	public void activateUser(User user) throws DaoException {
		getSqlMapClientTemplate().update("activateUser",user);
	}

	public void checkUserByNameOrEmail(String userName,String email)throws DaoException {
		User u=getUserByNameOrEmail(userName, email);
		if(u!=null){
			if(StringUtil.isNotEmpty(userName)){
				throw new DuplicateRecordException(ConsUtil.MSG_REGISTER_USERNAME_EXIST);
			}else{
				throw new DuplicateRecordException(ConsUtil.MSG_REGISTER_EMAIL_EXIST);
			}
		}
	}

	public User getUserByNameOrEmail(String userName,String email)throws DaoException {
		Map<String, String> paramMap=new HashMap<String, String>();
		paramMap.put("userName", userName);
		paramMap.put("email", email);
		List<User> users=(List<User>)getSqlMapClientTemplate().queryForList("getUserByNameOrEmail",paramMap);
		if(users!=null&&users.size()>0){
			return users.get(0);
		}
		return null;
	}

	@Override
	public User getUserByActivateCode(String activateCode) throws DaoException {
		return (User)getSqlMapClientTemplate().queryForObject("getUserByActivateCode", activateCode);
	}
	
	

}
